<template>
	<view class="page_content">
			<image style="width: 640rpx;height: 160rpx;margin-top: 176rpx auto 0;" src="@/static/images/3dzx_text.png"></image>
			<view class="text_24 text-center mb_16">（上传视频、创作自己的3D资产）</view>
			
			<view class="half_content_border mt_32"></view>
			<view class="page_content_border">
				<view class="mt_24">
					<u-upload v-if="!poster" :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" accept="video" :maxCount="1"
						width="352" height="352">
						<view class="flex_border_ridus video_border flex_center">
							<view class="small_border">
								<view class="flex_center"><u-icon slot="right" name="camera" size="48"></u-icon></view>
								<view class="mt_24 text-center mt_12">上传视频</view>
							</view>
						</view>
					</u-upload>
				</view>
				<image v-if="poster" @click="handleImage" :src="poster" :style="{width: screenWidth*2+'rpx',height: newHeight*2+'rpx'}"></image>
				<!-- 生成图片 -->
				<poster ref="poster" :list="list" background-color="#FFF" :width="screenWidth*2" :height="newHeight*2"
				    @on-success="posterSuccess" @on-error="posterError"></poster>

				<!-- <view class="flex_center_end">
					
				</view> -->

				<view v-if="poster" class="text_24 flex_center text-center mt_16 c_999">
					点击图片区域、可选择需要建模的物体
					<view class="pl_16" @click="handleReload"><u-icon size="20" name="reload"></u-icon></view>
				</view>
				<view class="b_FFF mt_24 flex_between_wrap cont-box">
					<image style="width: 24rpx;height: 96rpx;" src="@/static/images/img_left.png"></image>
					<u--input border="none" v-model="params.remark" placeholder="输入建模的物品名称"></u--input>
				    <image style="width: 24rpx;height: 96rpx;" src="@/static/images/img_right.png"></image>
				</view>
				<view class="b_FFF mt_24 flex_between_wrap" @click="showLevel = true">
					<image style="width: 24rpx;height: 96rpx;" src="@/static/images/img_left.png"></image>
					<u--input border="none" placeholder="请选择" v-model="params.modelName" disabled disabledColor="#ffffff"
						:suffixIcon="!showLevel ? 'arrow-down' : 'arrow-up'" suffixIconStyle="color: #909399"></u--input>
						<image style="width: 24rpx;height: 96rpx;" src="@/static/images/img_right.png"></image>
				</view>
				<u-action-sheet :show="showLevel" :actions="actions" @close="showLevel = false" @select="levelSelect">
				</u-action-sheet>
				<view class="mt_24">
					<view class="bac_btn"  @click="handleSumbit">确定生成我的3D资产</view>
				</view>
			</view>
			
			<view class="illustrate mt_24 flex_center" @click="showIllustrate = true">
				<u-icon slot="right" color="666666" name="question-circle"></u-icon>
				<view class="pl_16 c_666">视频拍摄详情说明</view>
			</view>
			<!-- <view class="c_999 font-20 mt_24">
				默认选择用户的第一张创作券，该券暂不做有限期设定。上传手机中的视频，调用后台服务，自动化完成建模任务；用户上传视频的建模，自动归类为3D单体化
			</view> -->
			<u-popup :show="showIllustrate" customStyle="width:90%" mode="center" :round="10">
				<view class="u_popup_level">
					<view class="pop_title">视频拍摄详情说明</view>
					<view>1）上传的视频需要动作连续，不能杂乱无章，需要按照顺时针或者逆时针，有顺序的拍摄，这样的生成的效果更逼真。</view>
					<view><br> 2）多角度拍摄，可以先拍近景、然后再拍远景，尽量多角度的去拍摄，这样呈现的效果也更加多元化。</view>
							<video style="width: 100%; height: 225px;margin-top: 12rpx;" src="https://platform.real-infinity.cn/outfile/video/802cd5f03b2390391d1d77a5ba98d1b3.mp4"/>
					<view class="flex_center mt_64">
						<view class="bac_btn"  @click="showIllustrate = false">我知道了</view>
					</view>
				</view>
			</u-popup>
	</view>
</template>

<script>
import { modelType, modelAdd } from '@/api/common.js'
import { getToken } from '@/utils/auth'
import config from '@/config'
import Poster from '@/components/zhangyuhao-poster/Poster.vue'
import { getBuildScope } from '@/api/common.js'
        
export default {
	components: {
	    Poster
	},
	data() {
		return {
			poster: '',
			list: [],
			screenWidth: 0,
			newHeight: 0,
			onInclickList: [],
			onInclick: [],
			fileList2: [],
			showLevel: false,
			showIllustrate: false,
			actions: [],
			videoContext: null,
			infoLogo: '',
			infoLargeLogo: '',
			params: {
				modelName: '',
				modelType: '',
				displayType: 2,
				originalFileName: 'xcx.mp4',
				video: '',
				videoPath: '',
				logo: '',
				remark: '',
				videoDuration: 0
			},
			uuid: ''
		}
	},
	onReady: function(res) {
			const query = uni.createSelectorQuery().in(this);
			query.select(".cont-box").boundingClientRect(res => {
			    this.screenWidth = res.width 
			}).exec();
	},
	onLoad() {
		modelType().then(res => {
			if (res.code == 200) {
				let data = res.data
				data.forEach(item => {
					item.name = item.dictLabel
				})
				this.actions = data
			}
		})
	},
	methods: {
		handleReload() {
			this.list = []
			this.onInclick = []
			this.poster = this.infoLargeLogo
			this.start()
			this.params.logo = this.infoLogo
			this.getImageSize()
		},
		handleImage(e){
			this.onInclick.push({
				x: e.detail.x - 35,
				y: e.detail.y - 215
			})
			this.start(e.detail.x - 35,e.detail.y - 215)
		},
		async getImageSize() {
		  let imageInfoObj = await uni.getImageInfo({src: this.poster}) 
		  // 取到图片的宽高
		  let { width,height } = imageInfoObj[1]
		  this.newHeight = height * this.screenWidth / width
		  this.start()
		},
		posterError(err) {
		    console.log(err)
		},
		posterSuccess(url) {
		    // 生成成功，会把临时路径在这里返回
		    this.poster = url;
		},
		start(x,y) {
			if(x&&y) {
				uni.showLoading({
					title: '物品识别提取中'
				});
				this.onInclickList.push({
					u : x / this.screenWidth,
					v : y  / this.newHeight
				})
				 getBuildScope({uuid:this.uuid,uvs:this.onInclickList}).then(res => {
				 	uni.hideLoading()
					this.poster = config.baseImg + res.data.painted_image_path
					this.start()
					this.params.logo = res.data.painted_image_path 
					this.getImageSize()
				 })
			}
		    // 赋值需要渲染的信息
		    this.list = [{
		            type: 'image',
		            // path替换成你自己的图片，注意需要在小程序开发设置中配置域名
		            path: this.poster,
		            x: 0,
		            y: 0,
		            width: this.screenWidth*2,
		            height: this.newHeight*2
		        }
		    ];
			if(this.onInclick.length > 0) {
				this.onInclick.forEach(item => {
					this.list.push({
						type: 'circular',
						x: item.x*2,
						y: item.y*2,
						width: 10,
						height: 10
					})
				})
			}
			// 生成图片
		    this.$nextTick(() => {
		        // 要放在$nextTick()里，不然会空白
		        this.$refs.poster.create();
		    })
		},
		handleSumbit() {
			if(!(this.params.modelName && this.params.videoPath)) {
				return 
			}
			this.params.uvs = this.onInclickList
			modelAdd(this.params).then(res => {
				if (res.code == 200) {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					setTimeout(function() {
						uni.navigateBack();
					}, 1000);
				}
			})
		},
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				const resultData = JSON.parse(result).data
				this.params.logo = resultData.logo
				this.infoLogo = resultData.logo
				this.poster = config.baseImg + resultData.logo
				this.infoLargeLogo = config.baseImg + resultData.logo
				this.uuid = resultData.uuid
				this.params.videoPath = resultData.pathName
				this.params.video = resultData.pathName
				this.params.videoDuration = resultData.videoDuration
				this.getImageSize()
				let item = this[`fileList${event.name}`][fileListLen]
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: config.baseImg + resultData.logo
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let that = this
				let a = uni.uploadFile({
					url: config.baseUrl+'/model/build-model/uploadVideo', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					header: {
						Authorization: getToken()
					},
					success: (res) => {
						setTimeout(() => {
							resolve(res.data)
						}, 1000)
					}
				});
			})
		},
		levelSelect(e) {
			this.params.modelName = e.name
			this.params.modelType = e.dictValue
			this.showLevel = false
		},
	}
}
</script>
<style scoped lang="scss">
.video_border {
	width: 352rpx;
	height: 352rpx;
	border-radius: 40rpx;
	border: 2rpx solid #00FFAA;
	margin: 8rpx auto 0;
	margin-left:50%;
	padding:16rpx;
}
.small_border {
	width: 320rpx;
	height: 320rpx;
	background: linear-gradient( 180deg, #00FFAA 0%, rgba(0,255,170,0.2) 100%);
	border-radius: 24rpx;
	padding-top:70rpx;
}
.illustrate {
	color: $uv-main-color;
	text-align: center;
}

.u_popup_level {
	padding: 28rpx;

	.pop_title {
		font-size: 36rpx;
		font-weight: 600;
		text-align: center;
		padding-bottom: 40rpx;
	}

	.pop_name {
		font-size: 30rpx;
		font-weight: 600;
		margin: 16rpx 0;
	}

	.btn {
		width: 45%;
		height: 72rpx;
		border-radius: 40rpx;
	}

	.agree {
		background: $uv-main-color;
		color: #FFFFFF;
	}
}

/deep/.u-upload__wrap__preview {
	width: 100%;
}
.page_content {
	background: url(https://platform.real-infinity.cn/images/3dzx_bac.png) no-repeat;
	background-size: 100% 100%;
	width: 100%;
	height: 100vh;
}
</style>